"""
初始化脚本数据库
"""
import json
import os
from .models import Script
from .sqlalchemy_database import SQLAlchemyDatabaseManager

def import_script_data():
    """
    导入script_data.json数据到数据库
    """
    db = SQLAlchemyDatabaseManager()
    session = db.get_session()
    
    try:
        # 获取数据文件路径
        current_dir = os.path.dirname(os.path.abspath(__file__))
        data_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(current_dir))), "data")
        json_file = os.path.join(data_dir, "script_data.json")
        
        if not os.path.exists(json_file):
            print(f"脚本数据文件不存在: {json_file}")
            return
            
        # 读取JSON数据
        with open(json_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
            
        # 导入数据
        for item in data:
            script = Script(
                name=item['name'],
                description=item.get('description'),
                type=item.get('type', 1),
                status=item.get('status', 1),
                config=item.get('config'),
                create_at=item.get('create_at'),
                update_at=item.get('update_at')
            )
            session.add(script)
            
        session.commit()
        print("脚本数据导入成功")
        
    except Exception as e:
        session.rollback()
        print(f"导入脚本数据时发生错误: {str(e)}")
    finally:
        session.close()

if __name__ == "__main__":
    import_script_data()
